﻿using Dapper;
using ERPEF;
using ERPEF.Model;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.IO;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class dict_imageController : ControllerBase
    {
        private readonly bs_dict_imageService bs_Dict_Image;
        private readonly MyDbContext myDbContext;
        public dict_imageController(MyDbContext myDb, bs_dict_imageService bs_Dict_ImageService)
        {
            myDbContext = myDb;
            bs_Dict_Image = bs_Dict_ImageService;
        }

        //产品查询
        [HttpGet]
        public async Task<IActionResult> Queryproducts()
        {
            var warehouse = await bs_Dict_Image.Queryproducts();
            if (warehouse != null)
            {
                return Ok(warehouse);
            }
            else
            {
                return NotFound("404");
            }
        }

        //产品逻辑删除
        [HttpDelete("{di_id}")]
        public async Task<IActionResult> productsDelete(int di_id)
        {
            int result = await bs_Dict_Image.productsDelete(di_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }

        //添加产品
        [HttpPost]
        public async Task<IActionResult> productsAdd(bs_dict_image dict_Image)
        {

            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxProductsNumber());

            // 生成新编码
            string newCode = GenerateSaleProducts(maxCodeNumber);

            dict_Image.di_code = newCode;

            if (ModelState.IsValid)
            {
                int result = await bs_Dict_Image.productsAdd(dict_Image);

                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //产品
        private async Task<string> GetMaxProductsNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxProductsString = await myDbContext.bs_dict_image
                .Where(w => w.di_code.StartsWith("CP"))
                .Select(w => w.di_code.Substring(10))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxProductsString))
            {
                return "1";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxProductsString);
            Console.WriteLine(maxCodeNumber);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }
        // 生成新的仓库编码
        private string GenerateSaleProducts(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "CP"、日期部分和数字部分
            return "CP" + dateString + codeString;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)

        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("No file uploaded.");
            }

            //判断文件类型
            var isImage = IsImage(file.FileName);

            //保存文件到服务器
            string folderPath = @"D:\qq\KaiFa\erp\S4Vue\public\images";

            Directory.CreateDirectory(folderPath);

            // 获取文件的完整路径
            var filePath = Path.Combine(folderPath, file.FileName);

            // 检查文件是否已存在
            if (System.IO.File.Exists(filePath))
            {
                return Content(filePath); // 文件已存在，直接返回文件路径
            }

            // 文件不存在，保存文件
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return Content(filePath);
        }

        private bool IsImage(string fileName)
        {
            var imageExtensions = new[] { ".jpg", ".jpeg", ".png", "gif" };
            var extension = Path.GetExtension(fileName);
            return imageExtensions.Contains(extension.ToLower());
        }

        //产品修改
        [HttpPut]
        public async Task<IActionResult> productsUpdate(bs_dict_image dict_Image)
        {
            if (ModelState.IsValid)
            {
                int result = await bs_Dict_Image.productsUpdate(dict_Image);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //配料查询
        [HttpGet]
        public async Task<IActionResult> Queryingredient()
        {
            var warehouse = await bs_Dict_Image.Queryingredient();
            if (warehouse != null)
            {
                return Ok(warehouse);
            }
            else
            {
                return NotFound("404");
            }
        }

        //配料逻辑删除
        [HttpDelete("{di_id}")]
        public async Task<IActionResult> ingredientDelete(int di_id)
        {
            int result = await bs_Dict_Image.ingredientDelete(di_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }

        //添加配料
        [HttpPost]
        public async Task<IActionResult> ingredientAdd(bs_dict_image dict_Image)
        {

            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxIngredientNumber());

            // 生成新编码
            string newCode = GenerateSaleIngredient(maxCodeNumber);

            dict_Image.di_code = newCode;

            if (ModelState.IsValid)
            {
                int result = await bs_Dict_Image.ingredientAdd(dict_Image);

                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //配料
        private async Task<string> GetMaxIngredientNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxProductsString = await myDbContext.bs_dict_image
                .Where(w => w.di_code.StartsWith("PL"))
                .Select(w => w.di_code.Substring(10))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxProductsString))
            {
                return "1";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxProductsString);
            Console.WriteLine(maxCodeNumber);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }
        // 生成新的仓库编码
        private string GenerateSaleIngredient(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "CP"、日期部分和数字部分
            return "PL" + dateString + codeString;
        }

        //配料修改
        [HttpPut]
        public async Task<IActionResult> ingredientUpdate(bs_dict_image dict_Image)
        {
            if (ModelState.IsValid)
            {
                int result = await bs_Dict_Image.ingredientUpdate(dict_Image);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //包装查询
        [HttpGet]
        public async Task<IActionResult> Querywrap()
        {
            var warehouse = await bs_Dict_Image.Querywrap();
            if (warehouse != null)
            {
                return Ok(warehouse);
            }
            else
            {
                return NotFound("404");
            }
        }

        //包装逻辑删除
        [HttpDelete("{di_id}")]
        public async Task<IActionResult> wrapDelete(int di_id)
        {
            int result = await bs_Dict_Image.wrapDelete(di_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }

        //添加包装
        [HttpPost]
        public async Task<IActionResult> wrapAdd(bs_dict_image dict_Image)
        {

            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxWrapNumber());

            // 生成新编码
            string newCode = GenerateSaleWrap(maxCodeNumber);

            dict_Image.di_code = newCode;
            if (ModelState.IsValid)
            {
                int result = await bs_Dict_Image.wrapAdd(dict_Image);

                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        private async Task<string> GetMaxWrapNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxProductsString = await myDbContext.bs_dict_image
                .Where(w => w.di_code.StartsWith("BZ"))
                .Select(w => w.di_code.Substring(10))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxProductsString))
            {
                return "1";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxProductsString);
            Console.WriteLine(maxCodeNumber);


            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }
        // 生成新的仓库编码
        private string GenerateSaleWrap(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "CP"、日期部分和数字部分
            return "BZ" + dateString + codeString;
        }


        //包装修改
        [HttpPut]
        public async Task<IActionResult> wrapUpdate(bs_dict_image dict_Image)
        {
            if (ModelState.IsValid)
            {
                int result = await bs_Dict_Image.wrapUpdate(dict_Image);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //产品分页
        [HttpGet]
        public ActionResult<FenYe<bs_dict_image>> getProductsFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "di_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "bs_dict_image"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<bs_dict_image>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<bs_dict_image> fenYe = new FenYe<bs_dict_image>()
                {
                    productsData = result,
                    Rows = row,
                };

                if (fenYe.productsData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //配料分页
        [HttpGet]
        public ActionResult<FenYe<bs_dict_image>> getIngredientFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "di_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "bs_dict_image"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<bs_dict_image>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<bs_dict_image> fenYe = new FenYe<bs_dict_image>()
                {
                    ingredientData = result,
                    Rows = row,
                };

                if (fenYe.ingredientData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //包装分页
        [HttpGet]
        public ActionResult<FenYe<bs_dict_image>> getWrapFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "di_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "bs_dict_image"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<bs_dict_image>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<bs_dict_image> fenYe = new FenYe<bs_dict_image>()
                {
                    wrapData = result,
                    Rows = row,
                };

                if (fenYe.wrapData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }
    }
}
